package cn.com.captureNetPacket.util;
import java.util.Arrays;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class SpringUtil implements ApplicationContextAware {
    private static SpringUtil   springUtil;
    
 
    public  static void setSpringUtil(SpringUtil   sprUtil){
        springUtil=sprUtil;
    }
 
    public static void  showApplicationInfo(){
    	 
        log.debug("Environment: {}",springUtil.applicationContext.getEnvironment());
        log.debug("ApplicationName: {} ,DisplayName: {} id: {} ",springUtil.applicationContext.getApplicationName(),springUtil.applicationContext.getDisplayName(),springUtil.applicationContext.getId());
        Arrays.stream(springUtil.applicationContext.getBeanDefinitionNames()).forEach(
                beanName->
                {
                	if(!beanName.contains("springframework"))
                    log.debug("beanName: {}",beanName);
                }
        );
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 通过beanName获取bean
     * @param beanName
     * @param <T>
     * @return
     */
    public  <T> T getBean(String beanName){
    	try {
        return (T)applicationContext.getBean(beanName);
    	}catch (Exception e) {
			return null;
		}
    }
    public static <T> T getUtilBean(String beanName){
    	try {
        return (T)springUtil.applicationContext.getBean(beanName);
    	}catch (Exception e) {
		return null;
    	}
    }

    /**
     * 通过bean的class获取bean
     * @param beanClass
     * @param <T>
     * @return
     */
    public  <T> T getBean(Class beanClass){
        return (T)applicationContext.getBean(beanClass);
    }
    public  static <T> T getUtilBean(Class beanClass){
    	log.debug("{}--------------------:{}",beanClass,springUtil.applicationContext.getBeansOfType(beanClass));
    	log.debug("-------------------->>:{}",springUtil.applicationContext.getBeanNamesForType(beanClass));
        return (T)springUtil.applicationContext.getBean(beanClass);
    }
    private ApplicationContext applicationContext;
}
